using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RiceShop.Models;
using RiceShop.Services;

namespace RiceShop.Controllers
{
    /// <summary>
    /// 商品分类控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CategoryController : ControllerBase
    {
        private readonly ICategoryService _categoryService;

        public CategoryController(ICategoryService categoryService)
        {
            _categoryService = categoryService;
        }

        /// <summary>
        /// 获取所有商品分类
        /// </summary>
        /// <returns>分类列表</returns>
        [HttpGet("list")]
        public async Task<ActionResult<IEnumerable<Category>>> GetCategories()
        {
            try
            {
                var categories = await _categoryService.GetCategoriesAsync();
                return Ok(ApiResponse<IEnumerable<Category>>.Ok(categories, "获取分类列表成功"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<IEnumerable<Category>>.Error($"获取分类列表失败: {ex.Message}"));
            }
        }

       /// <summary>
        /// 获取顶级商品分类
        /// </summary>
        /// <returns> 顶级商品分类列表</returns>
        [HttpGet("topList")]
        public async Task<ActionResult<IEnumerable<Category>>> GetTopCategories()
        {
            var categories = await _categoryService.GetTopCategoriesAsync();
            return Ok(ApiResponse<IEnumerable<Category>>.Ok(categories, "获取顶级菜单列表成功"));
        }

        /// <summary>
        /// 根据ID获取分类详情
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <returns>分类详情</returns>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult<Category>> GetCategory(long id)
        {
            try
            {
                var category = await _categoryService.GetCategoryByIdAsync(id);
                return Ok(ApiResponse<Category>.Ok(category, "获取分类详情成功"));
            }
            catch (KeyNotFoundException ex)
            {
                return NotFound(ApiResponse<Category>.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<Category>.Error($"获取分类详情失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 创建新分类
        /// </summary>
        /// <param name="category">分类信息</param>
        /// <returns>创建的分类信息</returns>
        [HttpPost("create")]
        public async Task<ActionResult<Category>> CreateCategory([FromBody] Category category)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ApiResponse<Category>.Error("无效的请求数据"));
                }

                var createdCategory = await _categoryService.CreateCategoryAsync(category);
                return CreatedAtAction(
                    nameof(GetCategory),
                    new { id = createdCategory.Id },
                    ApiResponse<Category>.Ok(createdCategory, "创建分类成功")
                );
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<Category>.Error($"创建分类失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 更新分类信息
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <param name="category">更新的分类信息</param>
        /// <returns>更新结果</returns>
        [HttpPut("update/{id}")]
        public async Task<ActionResult<Category>> UpdateCategory(long id, [FromBody] Category category)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ApiResponse<Category>.Error("无效的请求数据"));
                }

                var updatedCategory = await _categoryService.UpdateCategoryAsync(id, category);
                return Ok(ApiResponse<Category>.Ok(updatedCategory, "更新分类成功"));
            }
            catch (KeyNotFoundException ex)
            {
                return NotFound(ApiResponse<Category>.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<Category>.Error($"更新分类失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete/{id}")]

        public async Task<ActionResult> DeleteCategory(long id)
        {
            try
            {
                await _categoryService.DeleteCategoryAsync(id);
                return Ok(ApiResponse<object>.Ok(null, "删除分类成功"));
            }
            catch (KeyNotFoundException ex)
            {
                return NotFound(ApiResponse<object>.Error(ex.Message));
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ApiResponse<object>.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"删除分类失败: {ex.Message}"));
            }
        }
        
    }
}
